package com.gmss.crawler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.module.honor.domain.Honor;
import com.gmss.crawler.module.honor.service.IHonorService;
import com.gmss.crawler.module.person.domain.PersonInfo;
import com.gmss.crawler.module.resume.service.IResumeService;
import com.gmss.crawler.module.social.domain.Social;
import com.gmss.crawler.module.social.service.ISocialService;
import com.gmss.crawler.utils.CommonUtils;
import com.gmss.crawler.utils.CrawlerCommonUtils;
import com.gmss.crawler.utils.DateUtils;
import com.gmss.crawler.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 维基百科-爬虫
 */
@Slf4j
@Service
public class WikipediaCrawlerService {


    @Resource
    private BaiduBaiKeCrawlerService baiduBaiKeCrawlerService;

    // 结束关键字
    static List<String> overNameList = new ArrayList<String>() {{
        add("参考来源");
        add("参考链接");
        add("参考文献");
        add("参考资料");
        add("注释");
        add("外部链接");
        add("参见");
    }};

    public static void main(String[] args) throws IOException, InterruptedException {
        PersonInfo personInfo = new PersonInfo().builder().name("张志刚").id(2809L).build();
        new WikipediaCrawlerService().getWikiByPerson(personInfo, 1);
    }

    public void getWikiByPerson(PersonInfo personInfo, Integer type) throws InterruptedException, IOException {
        Document doc = null;
        String keyword = "";
        String name = personInfo.getName();
        if (type == 0) {
            keyword = "院士";
            doc = getWikiDocument(personInfo, type);
        } else if (type == 1) {
            keyword = "长江学者";
            doc = getWikiDocument(personInfo, type);
        } else {
            return;
        }

        if (null == doc || StringUtils.containsAny(doc.toString(), "电影", "导演") && !StringUtils.contains(doc.toString(), keyword)) {
            log.error("Document is null - 维基百科，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{}", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(),
                    personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName());
            return;
        }
        Map<String, String> wikiDetailMap = new HashMap<>();
        if (StringUtils.contains(doc.toString(), keyword)) {
            // 解析html
            wikiDetailMap = parseWikiDetail(doc, personInfo.getId());
            log.info("解析维基百科html后结果:{}", JSON.toJSONString(wikiDetailMap));
        } else {
            // 解析html
            wikiDetailMap = parseWikiDetail(doc, personInfo.getId());
            log.info("解析维基百科html后结果:{}", JSON.toJSONString(wikiDetailMap));
        }
        if (MapUtils.isEmpty(wikiDetailMap)) {
            log.error("wikiDetailMap is null - 维基百科，url条件：{}，人员id：{}，专业学科：{}，工作单位：{}，姓名：{}", personInfo.getName() + personInfo.getWorkCompany() + personInfo.getMajor(),
                    personInfo.getId(), personInfo.getMajor(), personInfo.getWorkCompany(), personInfo.getName());
            return;
        }

        // 逝世日期
        if (wikiDetailMap.containsKey("dateOfDeath") && StringUtils.isNotBlank(wikiDetailMap.get("dateOfDeath")) && StringUtils.isBlank(personInfo.getDateOfDeath())) {
            // 逝世日期大于当选年，说明查询出的人员信息不正确
            if (baiduBaiKeCrawlerService.judgeDateOfDeath(personInfo, type, wikiDetailMap, "dateOfDeath")) return;
            personInfo.setDateOfDeath(wikiDetailMap.get("dateOfDeath"));
        }

        if (wikiDetailMap.containsKey("descData") && StringUtils.isNotBlank(wikiDetailMap.get("descData")) && StringUtils.isBlank(personInfo.getDescribeData())) {
            personInfo.setDescribeData(wikiDetailMap.get("descData"));
        }
        if (wikiDetailMap.containsKey("foreignName") && StringUtils.isNotBlank(wikiDetailMap.get("foreignName")) && StringUtils.isBlank(personInfo.getForeignName())) {
            personInfo.setForeignName(wikiDetailMap.get("foreignName"));
        }
        if (wikiDetailMap.containsKey("nationality") && StringUtils.isNotBlank(wikiDetailMap.get("nationality")) && StringUtils.isBlank(personInfo.getNationality())) {
            personInfo.setNationality(wikiDetailMap.get("nationality"));
        }
        if (wikiDetailMap.containsKey("politicalParty") && StringUtils.isNotBlank(wikiDetailMap.get("politicalParty")) && StringUtils.isBlank(personInfo.getPoliticalParty())) {
            personInfo.setPoliticalParty(wikiDetailMap.get("politicalParty"));
        }
        if (wikiDetailMap.containsKey("birthday") && StringUtils.isNotBlank(wikiDetailMap.get("birthday")) && StringUtils.isBlank(personInfo.getBirthday())) {
            personInfo.setBirthday(wikiDetailMap.get("birthday"));
        }
        if (wikiDetailMap.containsKey("birthplace") && StringUtils.isNotBlank(wikiDetailMap.get("birthplace")) && StringUtils.isBlank(personInfo.getBirthplace())) {
            personInfo.setBirthplace(wikiDetailMap.get("birthplace"));
        }
        if (wikiDetailMap.containsKey("sex") && StringUtils.isNotBlank(wikiDetailMap.get("sex")) && StringUtils.isBlank(personInfo.getSex())) {
            personInfo.setSex(wikiDetailMap.get("sex"));
        }
        if (wikiDetailMap.containsKey("research") && StringUtils.isNotBlank(wikiDetailMap.get("research")) && StringUtils.isBlank(personInfo.getResearchContents())) {
            personInfo.setResearchContents(wikiDetailMap.get("research"));
        }
        if (wikiDetailMap.containsKey("degree") && StringUtils.isNotBlank(wikiDetailMap.get("degree")) && StringUtils.isBlank(personInfo.getAcademicDegree())) {
            personInfo.setAcademicDegree(wikiDetailMap.get("degree"));
        }
        if (wikiDetailMap.containsKey("resumeData") && StringUtils.isNotBlank(wikiDetailMap.get("resumeData"))) {
            String data = wikiDetailMap.get("resumeData");
            if (!wikiDetailMap.containsKey("birthplace") && StringUtils.isBlank(personInfo.getBirthplace())) {
                baiduBaiKeCrawlerService.getBirthplaceByResume(personInfo, data);
            }
            if (!wikiDetailMap.containsKey("birthday") && StringUtils.isBlank(personInfo.getBirthday())) {
                baiduBaiKeCrawlerService.getBirthdayByResume(personInfo, data);
            }
            baiduBaiKeCrawlerService.saveResumeData(personInfo, type, wikiDetailMap);
        }
        if (wikiDetailMap.containsKey("socialData") && StringUtils.isNotBlank(wikiDetailMap.get("socialData"))) {
            baiduBaiKeCrawlerService.saveSocialData(personInfo, type, wikiDetailMap, "socialData");
        }
        if (wikiDetailMap.containsKey("scientificResult") && StringUtils.isNotBlank(wikiDetailMap.get("scientificResult"))) {
            baiduBaiKeCrawlerService.saveHonorData(personInfo, type, wikiDetailMap, "scientificResult", "honorsData");
        }
        if (wikiDetailMap.containsKey("honorsData") && StringUtils.isNotBlank(wikiDetailMap.get("honorsData"))) {
            baiduBaiKeCrawlerService.saveHonorData(personInfo, type, wikiDetailMap, "honorsData", "scientificResult");
        }


    }

    private Document getWikiDocument(PersonInfo personInfo, Integer type) throws InterruptedException {
        Document doc = null;
        String major = personInfo.getMajor();
        String userName = personInfo.getName();
        String workCompany = personInfo.getWorkCompany();

        // 获取维基百科人名搜索结果
        String namePath = null;
        String keyword = null;
        if (type == 1) {
            String relatedLinks = personInfo.getRelatedLinks();
            JSONObject jsonObject = JSONObject.parseObject(relatedLinks);
            namePath = jsonObject.getString("relatedLinksUrl");
//            doc = CrawlerCommonUtils.getDocument(namePath);
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/1999-维基百科-张志刚.html");
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/2009-维基百科-余纪元.html");
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/2851-维基百科-凯.html");
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/5060-维基百科-吴瑛.html");
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/3772-维基百科-梁梁.html");
//            doc = CrawlerCommonUtils.getDocumentHtml("/htmlTest/cj-长江学者/person/3740-维基百科-钟扬.html");
            doc = CrawlerCommonUtils.getDocumentByFile("C:\\Users\\user\\Desktop\\3.html");
        } else if (type == 0) {
        } else if (StringUtils.isNotBlank(workCompany)) {
        } else {
            return null;
        }


        return doc;
    }

    /**
     * 维基百科详情页面解析
     *
     * @param doc
     * @return
     * @throws InterruptedException
     */
    private Map<String, String> parseWikiDetail(Document doc, Long id) {
        Map<String, String> wikiDetailMap = new HashMap<>();
        // 解析html
        Element contentTextElement = doc.getElementById("mw-content-text");
        Elements partserOutput = contentTextElement.select(".mw-parser-output");
        Elements pList = partserOutput.select("p");
        // 个人简介
        if (null != pList && pList.size() > 0) {
            String descData = pList.get(0).text();
            if (StringUtils.isNotBlank(descData)) {
                descData = RegexUtils.replaceData(descData, RegexUtils.ALL_ZHONG_REGEX, "");
                wikiDetailMap.put("descData", descData);
                if (descData.contains("（") && descData.contains("）")) {
                    descData = descData.replaceAll("（", "(").replaceAll("）", ")");
                    // 获取出生日期和逝世日期、外文名
                    getBirthdayAndDateOfDeah(wikiDetailMap, descData);
                }
                // 获取性别
                getSex(wikiDetailMap, descData);
                // 获取出生地
                getBirthplace(wikiDetailMap, descData);
                // 获取民族
                getNation(wikiDetailMap, descData);
                // 获取学位
                String degree = baiduBaiKeCrawlerService.setProperty(wikiDetailMap, descData, "学位");
                if (wikiDetailMap.containsKey("学位"))
                    wikiDetailMap.remove("学位");
                if (StringUtils.isNotBlank(degree))
                    wikiDetailMap.put("degree", degree);
                // 获取政党
                getPoliticalParty(wikiDetailMap, descData);
                // 获取国籍
                getNationality(wikiDetailMap, descData);
            }
        }

        // 目录Map
        Map<Integer, String> menuMap = new LinkedHashMap<>();
        Element tocElement = doc.getElementById("toc");
        if (null != tocElement) {
            Elements menus = tocElement.select("ul");
            if (menus.size() > 0) {
                menus = menus.get(0).select("li").select("a");
            }
            for (int i = 0; i < menus.size(); i++) {
                String tocnumber = menus.get(i).select(".tocnumber").text();
                String toctext = menus.get(i).select(".toctext").text();
                try {
                    Integer keyIndex = Integer.parseInt(tocnumber);
                    if (!menuMap.containsKey(menuMap))
                        menuMap.put(keyIndex - 1, toctext);
                } catch (NumberFormatException e) {
                    // 异常说明是子目录，暂时不处理
                }
            }
        }

        // 目录及对应的html区域
        Map<Integer, String> menuDetailMap = new LinkedHashMap<>();
        // 存在目录
        if (MapUtils.isNotEmpty(menuMap)) {
            parseMenu(id, wikiDetailMap, partserOutput, menuMap, menuDetailMap);

        } else {
            // 页面里有h2标签的，当做是目录
            Elements hElements = partserOutput.select("h2");
            for (int i = 0; i < hElements.size(); i++) {
                String text = hElements.get(i).text();
                text = RegexUtils.replaceData(text, RegexUtils.ALL_ZHONG_REGEX, "");
                if (StringUtils.isNotBlank(text)) {
                    menuMap.put(i, text);
                }
            }
            parseMenu(id, wikiDetailMap, partserOutput, menuMap, menuDetailMap);

            // 没有目录，也没有h2标签
            if (MapUtils.isEmpty(menuMap) && null != pList && pList.size() > 0) {
                List<String> resumeList = new ArrayList<>();
                for (int i = 1; i < pList.size(); i++) {
                    resumeList.add(pList.get(i).text());
                }
                if (!wikiDetailMap.containsKey("resumeData") && CollectionUtils.isNotEmpty(resumeList))
                    wikiDetailMap.put("resumeData", JSON.toJSONString(resumeList));

            }
        }
        return wikiDetailMap;
    }

    private void parseMenu(Long id, Map<String, String> wikiDetailMap, Elements partserOutput, Map<Integer, String> menuMap, Map<Integer, String> menuDetailMap) {
        menuMap.forEach((key, value) -> {
            String partserOutputStr = partserOutput.toString();
            if (partserOutputStr.lastIndexOf(value) > 0) {
                partserOutputStr = partserOutputStr.substring(partserOutputStr.lastIndexOf(value), partserOutputStr.length());
            }
            if (key == menuMap.size() - 1 || overNameList.contains(value)) {
                return;
            }
            String nextValue = menuMap.get((key + 1));
            if (partserOutputStr.indexOf(value) >= 0 && partserOutputStr.indexOf(nextValue) > 0) {
                String detailData = partserOutputStr.substring(partserOutputStr.indexOf(value), partserOutputStr.indexOf(nextValue));
                menuDetailMap.put(key, detailData);
            }
        });
        if (MapUtils.isNotEmpty(menuDetailMap)) {
            List<String> resumeList = new ArrayList<>();
            List<Social> socialList = new ArrayList<>();
            List<Honor> scientificList = new ArrayList<>();
            List<Honor> honorList = new ArrayList<>();
            menuDetailMap.forEach((key, value) -> {
                String menuValue = menuMap.get(key);
                value = RegexUtils.replaceData(value, RegexUtils.ALL_ZHONG_REGEX, "");
                // 人物经历
                getResumeDetail(wikiDetailMap, resumeList, value, menuValue);
                // 研究方向
                getResearchDetail(wikiDetailMap, value, menuValue);
                // 社会任职
                getSocialDetail(id, wikiDetailMap, socialList, value, menuValue);
                // 科研奖项
                getHonorDetail(id, wikiDetailMap, scientificList, value, menuValue, BaiduBaiKeCrawlerService.scientificNameList, 0, "scientificResult");
                // 荣誉
                getHonorDetail(id, wikiDetailMap, honorList, value, menuValue, BaiduBaiKeCrawlerService.honorNameList, 1, "honorsData");

            });
        }
    }

    /**
     * 获取社会任职
     *
     * @param id
     * @param wikiDetailMap
     * @param socialList
     * @param value
     * @param menuValue
     */
    private void getSocialDetail(Long id, Map<String, String> wikiDetailMap, List<Social> socialList, String value, String menuValue) {
        if (BaiduBaiKeCrawlerService.socialNameList.contains(menuValue)) {
            Document docByString = CrawlerCommonUtils.getDocumentByString(value);
            Elements elements = docByString.select("p");
            for (int i = 0; i < elements.size(); i++) {
                String text = elements.get(i).text();
                text = text.replaceAll("，", ",");
                String[] texts = text.split("。");
                for (int j = 0; j < texts.length; j++) {
                    if (StringUtils.isNotBlank(texts[j])) {
                        Social duties = new Social().builder().personId(id).duties(texts[j]).build();
                        socialList.add(duties);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(socialList))
                wikiDetailMap.put("socialData", JSON.toJSONString(socialList));
        }
    }

    /**
     * 获取研究方向、研究领域
     *
     * @param wikiDetailMap
     * @param value
     * @param menuValue
     */
    private void getResearchDetail(Map<String, String> wikiDetailMap, String value, String menuValue) {
        if (BaiduBaiKeCrawlerService.researchNameList.contains(menuValue)) {
            Document docByString = CrawlerCommonUtils.getDocumentByString(value);
            String researchContentElements = docByString.select("p").text();
            if (StringUtils.isBlank(researchContentElements))
                researchContentElements = docByString.select("body").text();
            if (StringUtils.isNotBlank(researchContentElements))
                wikiDetailMap.put("research", researchContentElements);
        }
    }

    /**
     * 获取人物经历、生平
     *
     * @param wikiDetailMap 保存html解析结果的map
     * @param resumeList    人物经历、生平数据集合
     * @param value         html字符串
     * @param menuValue     目录名称
     */
    private void getResumeDetail(Map<String, String> wikiDetailMap, List<String> resumeList, String value, String menuValue) {
        if (BaiduBaiKeCrawlerService.resumeNameList.contains(menuValue)) {
            Document docByString = CrawlerCommonUtils.getDocumentByString(value);
            // 第一种格式，数据在P标签里。
            Elements pResumes = docByString.select("p");
            for (int i = 0; i < pResumes.size(); i++) {
                String text = pResumes.get(i).text();
                text = text.replaceAll("，", ",");
                String[] texts = text.split("。");
                for (int j = 0; j < texts.length; j++) {
                    if (StringUtils.isNotBlank(texts[j])) {
//                        Resume resume = new Resume().builder().personId(id).resume(texts[j]).build();
                        resumeList.add(texts[j]);
                    }
                }
            }
            if (CollectionUtils.isEmpty(resumeList)) {
                // 第二种格式，数据在ul li标签里。
                Elements elements = docByString.select("ul li");
                for (int i = 0; i < elements.size(); i++) {
                    String text = elements.get(i).text();
                    text = text.replaceAll("，", ",");
//                    Resume resume = new Resume().builder().personId(id).resume(text).build();
                    resumeList.add(text);
                }
            }


            if (CollectionUtils.isNotEmpty(resumeList))
                wikiDetailMap.put("resumeData", JSON.toJSONString(resumeList));
        }
    }

    /**
     * 获取科研奖项/荣誉
     *
     * @param id            人员id
     * @param wikiDetailMap 保存html解析结果的map
     * @param honorList     科研奖项/荣誉数据集合
     * @param value         html字符串
     * @param menuValue     目录名称
     * @param nameList      科研奖项/荣誉解析的名称
     * @param type          0：科研奖项，1：荣誉
     * @param key           保存wikiDetailMap的key
     */
    private void getHonorDetail(Long id, Map<String, String> wikiDetailMap, List<Honor> honorList,
                                String value, String menuValue, List<String> nameList, int type, String key) {
        if (nameList.contains(menuValue)) {
            // 获取科研奖项/荣誉
            getHonorDataByWiki(id, honorList, value, type);
            if (!wikiDetailMap.containsKey(key) && CollectionUtils.isNotEmpty(honorList))
                wikiDetailMap.put(key, JSON.toJSONString(honorList));
        }
    }

    /**
     * 获取科研奖项/荣誉
     *
     * @param id        人员id
     * @param honorList 科研奖项/荣誉数据集合
     * @param value     html字符串
     * @param type      0：科研奖项，1：荣誉
     */
    private void getHonorDataByWiki(Long id, List<Honor> honorList, String value, Integer type) {
        Document docByString = CrawlerCommonUtils.getDocumentByString(value);
        Elements elements = docByString.select("ul li");
        for (int i = 0; i < elements.size(); i++) {
            String text = elements.get(i).text();
            text = text.replaceAll("，", ",");
            if (StringUtils.contains(text, ",") && text.indexOf(",") > 0) {
                String date = text.substring(0, text.indexOf(","));
                String detail = text.substring(text.indexOf(",") + 1, text.length());
                // 科研奖项/荣誉 处理
                Honor honor = handleHonorByData(id, type, text, date, detail);
                honorList.add(honor);
            } else if (StringUtils.contains(text, " ") && text.indexOf(" ") > 0) {
                String date = text.substring(0, text.indexOf(" "));
                String detail = text.substring(text.indexOf(" ") + 1, text.length());
                // 科研奖项/荣誉 处理
                Honor honor = handleHonorByData(id, type, text, date, detail);
                honorList.add(honor);
            } else {
                Honor honor = new Honor().builder().personId(id).type(type).build();
//                baiduBaiKeCrawlerService.getPrizeLevel(honor, text);
//                baiduBaiKeCrawlerService.getAwardLevel(honor, text);
//                honor.setPrizeName(text);
                baiduBaiKeCrawlerService.setHonorData(honor, text, text);
                honorList.add(honor);
            }
        }
        // 不是ul格式，再根据p标签获取
        if (CollectionUtils.isEmpty(honorList)) {
            Elements ps = docByString.select("p");
            for (int i = 0; i < ps.size(); i++) {
                String pText = ps.get(i).text();
                if (StringUtils.isNotBlank(pText)) {
                    String[] pTextSplit = pText.split("。");
                    for (int j = 0; j < pTextSplit.length; j++) {
                        String text = pTextSplit[j];
                        // 科研奖项/荣誉 处理
                        Honor honor = handleHonorByData(id, type, text, text, text);
                        honorList.add(honor);
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(honorList)) {
            Elements ps = docByString.select("body");
            for (int i = 0; i < ps.size(); i++) {
                String pText = ps.get(i).text();
                if (StringUtils.isNotBlank(pText)) {
                    String[] pTextSplit = pText.split("。");
                    for (int j = 0; j < pTextSplit.length; j++) {
                        String text = pTextSplit[j];
                        // 科研奖项/荣誉 处理
                        Honor honor = handleHonorByData(id, type, text, text, text);
                        honorList.add(honor);
                    }
                }
            }
        }

    }

    /**
     * 科研奖项/荣誉 处理
     *
     * @param id     人员id
     * @param type   0：科研奖项，1：荣誉
     * @param text   完整数据
     * @param date   完整数据中，分离出来的日期数据
     * @param detail 完整数据中，分离出来的详情数据
     * @return
     */
    private Honor handleHonorByData(Long id, Integer type, String text, String date, String detail) {
        Honor honor = new Honor().builder().personId(id).type(type).build();
        try {
            honor.setHonorDate(DateUtils.handleDate(date));
            baiduBaiKeCrawlerService.setHonorData(honor, text, detail);
//            honor.setPrizeName(detail);
        } catch (Exception e) {
            baiduBaiKeCrawlerService.setHonorData(honor, text, text);
//            honor.setPrizeName(text);
        }
        return honor;
    }
//
//    private Honor handleHonorByData(Long id, Integer type, String text, String date, String detail) {
//        Honor honor = new Honor().builder().personId(id).type(type).build();
//        try {
//            honor.setHonorDate(DateUtils.handleDate(date));
//            baiduBaiKeCrawlerService.getPrizeLevel(honor, detail);
//            baiduBaiKeCrawlerService.getAwardLevel(honor, detail);
//            honor.setPrizeName(detail);
//        } catch (Exception e) {
//            baiduBaiKeCrawlerService.getPrizeLevel(honor, text);
//            baiduBaiKeCrawlerService.getAwardLevel(honor, text);
//            honor.setPrizeName(text);
//        }
//        return honor;
//    }

    /**
     * 获取性别
     *
     * @param wikiDetailMap
     */
    public void getSex(Map<String, String> wikiDetailMap, String descData) {
        descData = descData.replaceAll("，", ",");
        if (StringUtils.containsAny(descData, ",男,", "，男，")) {
            wikiDetailMap.put("sex", "男");
        } else if (StringUtils.containsAny(descData, ",女,", "，女，")) {
            wikiDetailMap.put("sex", "女");
        }
    }

    /**
     * 获取民族
     *
     * @param wikiDetailMap
     * @param descData
     */
    public void getNation(Map<String, String> wikiDetailMap, String descData) {
        if (StringUtils.isNotBlank(descData)) {
            for (String nationStr : Constants.NATION_BANE_LIST) {
                if (StringUtils.contains(descData, nationStr)) {
                    wikiDetailMap.put("nation", nationStr);
                    return;
                }
            }
        }
    }

    /**
     * 获取出生地
     *
     * @param wikiDetailMap
     * @param descData
     */
    public void getBirthplace(Map<String, String> wikiDetailMap, String descData) {
        if (StringUtils.isNotBlank(descData)) {
            descData = descData.replaceAll("，", ",");
            String birthplace = RegexUtils.getTextContent(descData, RegexUtils.BIRTHPLACE);
            if (StringUtils.isBlank(birthplace)) {
                birthplace = RegexUtils.getTextContent(descData, RegexUtils.BIRTHPLACE_TWO);
            }
            if (StringUtils.isNotBlank(birthplace))
                wikiDetailMap.put("birthplace", birthplace);
        }
    }

    /**
     * 获取出生日期和逝世日期、外文名
     *
     * @param wikiDetailMap
     * @param descData
     */
    public void getBirthdayAndDateOfDeah(Map<String, String> wikiDetailMap, String descData) {
        if (StringUtils.isNotBlank(descData)) {
            descData = descData.replaceAll("，", ",");
            String birthdayData = RegexUtils.getTextContent(descData, RegexUtils.ALL_KUA_REGEX_TWO);
            if (StringUtils.isBlank(birthdayData))
                return;

            if (birthdayData.indexOf(",") > 0) {
                String[] birthdayDatas = birthdayData.split(",");
                if (StringUtils.isNotBlank(birthdayDatas[0])) {
                    String foreignNameData = birthdayDatas[0].replaceAll("：", ":");
                    if (foreignNameData.indexOf(":") > 0) {
                        String[] foreignNameSplit = foreignNameData.split(":");
                        if (foreignNameSplit.length > 1 && StringUtils.isNotBlank(foreignNameSplit[1])) {
                            //外文名
                            wikiDetailMap.put("foreignName", foreignNameSplit[1]);
                        }
                    } else {
                        //外文名
                        wikiDetailMap.put("foreignName", birthdayDatas[0]);
                    }
                }
            }
            if (birthdayData.indexOf("－") > 0) {
                String[] birthdayDatas = birthdayData.split("－");
                String birthday = "";
                String dateOfDeath = "";
                if (birthdayDatas.length >= 1)
                    birthday = CommonUtils.getBirthdayByString(birthdayDatas[0]);
                if (birthdayDatas.length >= 2)
                    dateOfDeath = CommonUtils.getBirthdayByString(birthdayDatas[1]);
                if (StringUtils.isNotBlank(birthday)) {
                    wikiDetailMap.put("birthday", birthday);
                }
                if (StringUtils.isNotBlank(dateOfDeath)) {
                    wikiDetailMap.put("dateOfDeath", dateOfDeath);
                }
            }
        }
    }

    /**
     * 获取国籍
     *
     * @param wikiDetailMap
     * @param descData
     */
    private void getNationality(Map<String, String> wikiDetailMap, String descData) {
        if (StringUtils.isNotBlank(descData)) {
            descData = descData.replaceAll("，", ",");
            String nationality = RegexUtils.getTextContent(descData, RegexUtils.NATIONALITY);
            if (StringUtils.isNotBlank(nationality)) {
                String[] datas = nationality.split(",");
                wikiDetailMap.put("nationality", datas[datas.length - 1] + "籍华人");
            }
        }
    }

    /**
     * 获取政党
     *
     * @param wikiDetailMap
     * @param descData
     */
    public void getPoliticalParty(Map<String, String> wikiDetailMap, String descData) {
        if (StringUtils.isNotBlank(descData) && StringUtils.containsAny(descData, "中共党员", "中国共产党党员")) {
            wikiDetailMap.put("politicalParty", "中共党员");
        }
    }
}
